package com.lance.answer.question_answer.xj_new;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.GkUser;
import com.lance.answer.dto.XjStudentCourseInfo;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.video.dto.WatchVideoDto;
import com.lance.answer.util.Constant;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

/**
 * @author fengx
 * 获取新疆一体化 每个学生的课程信息
 */
@Slf4j
public class GetXjStudentCourseInfoTask  extends Thread {

    private final String driverPath;
    private final LinkedBlockingDeque<GkUser> users;

    public GetXjStudentCourseInfoTask(String driverPath,  LinkedBlockingDeque<GkUser>  users) {
        this.driverPath = driverPath;
        this.users = users;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (users.size() > 0) {
            GkUser  gkUser = users.take();
            String userName = gkUser.getUsername();
            String password = gkUser.getPwd();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), users.size(), userName, password);
            System.err.println("执行任务11111");
            get(userName,password);
        }

        if (users.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }




    public static void get(String username, String pwd) throws IOException {



        WebDriver driver = Util.getDriver("c:\\ynouAutoStudy\\chromedriver.exe");
        try {
            driver.get("https://xjskk.open.com.cn/stuspace-auth/#/login");
            XinJiangUtil.studentLogin(driver, username, pwd);
            Thread.sleep(4000);
            // FIXME 有的人报了多个专业
           try{
              WebElement we = findWeElements(driver, "div[class='part']", 20).get(0);
                   System.err.println("we.getAttribute(\"title\")):" + we.getAttribute("title"));
                   // FIXME 正式要删掉
                   String title = we.getAttribute("title");
                   LinkedList<String> list = Lists.newLinkedList();
               list.add("2022年秋季");
               list.add("2022秋季");
               list.add("2022年春季");
               list.add("2022春季");
                   list.add("2021年秋季");
                   list.add("2021秋季");
                   list.add("2021年春季");
                   list.add("2021春季");
                   list.add("2020年秋季");
                   list.add("2020秋季");
                   list.add("2020年春季");
                   list.add("2020春季");
                   list.add("2019年秋季");
                   list.add("2019秋季");
                   list.add("2019年春季");
                   list.add("2019春季");
                   for (String s : list) {
                       if (title.contains(s)) {
                           we.click();
                           break;
                       }
                   }

                   // FIXME 正式要删掉

           }catch (Exception e1){

           }

            Thread.sleep(5000);
            Set<Cookie> cookies = driver.manage().getCookies();
            String studentSpaceProfile = Util.getStudentSpaceProfile2(cookies);
            String authorization = Util.getAuthorization2(cookies);
            Map<String, String> heads = Maps.newHashMap();
            String cookie = Util.getCookie(cookies);
            initHeads(heads, studentSpaceProfile, authorization);



            String getCourseInfoUrl = "https://xjskk.open.com.cn/api/student/student-space-service/courses/" +
                    "getStudentCourses?pageNumber=1&pageSize=2000000&status=1&courseNameCode=";
            XjStudentCourseInfo xjStudentCourseInfo = JSON.parseObject(HttpUtil.get(getCourseInfoUrl, cookie, heads),
                    XjStudentCourseInfo.class);

            String getTeseCourseInfo = "https://xjskk.open.com.cn/api/student/student-space-service/courses" +
                    "/getStudentThinkPoliticsCoursesV2?pageNumber=1&pageSize=2000000&courseNameCode=";
            XjStudentCourseInfo teseCourseInfo = JSON.parseObject(HttpUtil.get(getTeseCourseInfo, cookie, heads),
                    XjStudentCourseInfo.class);

            XjStudentCourseInfo.ContentDTO contentDTO = xjStudentCourseInfo.getContent();
            List<XjStudentCourseInfo.ContentDTO.ItemsDTO> itemsDTOS = contentDTO.getItems();

            // 把特色课程也加进去；
            for(XjStudentCourseInfo.ContentDTO.ItemsDTO itemsDTO:teseCourseInfo.getContent().getItems()){
                itemsDTOS.add(itemsDTO);
            }
            contentDTO.setItems(itemsDTOS);
            xjStudentCourseInfo.setContent(contentDTO);



            // 原始的
            FileUtils.write(new File("E:\\XjStudentCourseInfoTmp\\origin\\"  + username+".json"), JSONObject.toJSONString(xjStudentCourseInfo, SerializerFeature.PrettyFormat),
                    "utf-8");


            FileUtils.write(new File("E:\\XjStudentCourseInfoTmp\\deal\\"  + username+".json"), JSONObject.toJSONString(xjStudentCourseInfo.getContent().getItems(), SerializerFeature.PrettyFormat),
                    "utf-8");





        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e) {

            }
        }
    }












    public static void initHeads(Map<String, String> heads, String studentSpaceProfile, String authorization) {
        heads.put("referer", "https://xjskk.open.com.cn/stuspace/");
        heads.put("authority", "xjskk.open.com.cn");
        heads.put("path", "/api/student/student-space-service/resources/updateResourceTrace");
        heads.put("scheme", "scheme");
        heads.put("open-student-space-profile", studentSpaceProfile);
        heads.put("origin", "https://xjskk.open.com.cn");
        heads.put("authorization", authorization);
    }




}
